﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cmdLineParserModule;

namespace cmdLineParserModule
{
    /// <summary>
    /// Option class for marking enum attribute, usable with 'string' only
    /// </summary>
    public class optionEnumAttribute : optionParametrizedAttribute
    {
        /// <summary>
        /// Array of values accepted by parser
        /// </summary>
        public string[] valueList = null;

        /// <summary>
        /// Type of property marked by this class
        /// </summary>
        /// <returns>Only accepted type of property</returns>
        internal override Type typeAccepted()
        {
            return typeof(string);
        }

        /// <summary>
        /// Creates string value from string and checks validity of the value
        /// </summary>
        /// <param name="stringValue">String value that is checked</param>
        /// <returns>Original string value or throws WrongUsageException, if stringValue is not in valueList</returns>
        internal override object createValueFromString(string stringValue)
        {
            if (!valueList.Contains(stringValue))
            {
                string optionList = "";
                foreach (string option in this.valueList)
                    optionList += string.Format("'{0}'{1}", option, ", ");

                // removal of last ", " in optionList
                if (optionList.EndsWith(", "))
                    optionList = optionList.Substring(0, optionList.Length - 2);

                throw new WrongUsageException("'{0}' is not an option in enumerated values, only {1} allowed.", stringValue, optionList);
            }
            else
            {
                return stringValue;
            }
        }


        /// <summary>
        /// Checks valid definition of class (value list must not be empty, defaultValue must be contained in list)
        /// </summary>
        protected override void customCheck()
        {
            base.customCheck();

            if (valueList == null || valueList.Count() == 0)
                throw new WrongDefinitionException("Property {0} has no enum values specified.", fieldFullName());

            if (defaultValue != null)
            {
                if (!valueList.Contains(defaultValue))
                    throw new WrongDefinitionException("Property {0} has defaultValue specified as '{1}', although this value is not contained in enumerated values.", fieldFullName(), defaultValue);
            }
        }
    }
}
